<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { OrderQueryParams, OrderItem } from '@/api/order/types'
import { getOrderPageList } from '@/api/order/admin'
import { useRouter } from 'vue-router' // 新增导入
import { orderStatusMap } from '@/constants/order'
import { ContentWrap } from '@/components/ContentWrap'

// 搜索表单初始数据
const searchFormInit = {
  userId: '',
  userName: '',
  skuId: '',
  skuCode: '',
  pvValue: '',
  orderStatus: '-1'
}

// 搜索表单数据
const searchForm = reactive({ ...searchFormInit })

// 数据状态
const orderList = ref<OrderItem[]>([])
const loading = ref(false)
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    // 构造查询参数
    const params: OrderQueryParams = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize
    }

    // 只添加非空/默认值的搜索条件
    if (searchForm.userId > 0) {
      params.userId = searchForm.userId
    }
    if (searchForm.skuId > 0) {
      params.skuId = searchForm.skuId
    }
    if (searchForm.pvValue) {
      params.pvValue = searchForm.pvValue
    }
    if (searchForm.orderStatus !== -1) {
      params.orderStatus = searchForm.orderStatus
    }

    const response = await getOrderPageList(params)
    if (response.code === 200) {
      orderList.value = response.data
      pagination.value.total = response.data.length // 实际应从接口获取总数
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchOrderList()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, searchFormInit)
  pagination.value.currentPage = 1
  fetchOrderList()
}

// 订单状态映射
const getOrderStatusText = (status: number): string => {
  return orderStatusMap[status] || '未知状态'
}
// 查看订单详情
const jumpDetailPage = (data: any) => {
  router.push({
    name: 'OrderDetail',
    query: { orderNo: data.orderNo }
  })
}

// 删除订单
const deleteOrder = (order: OrderItem) => {
  ElMessageBox.confirm(`确定要删除订单 ${order.orderNo} 吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 执行删除操作
      ElMessage.success('删除成功')
      // 重新获取列表
      fetchOrderList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  fetchOrderList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  fetchOrderList()
}

// 初始化
onMounted(() => {
  fetchOrderList()
})

// 获取路由实例
const router = useRouter()
// 跳转到创建订单页面
const gotoPlaceOrder = () => {
  router.push('/order/place-order')
}
</script>
<template>
  <ContentWrap title="订单列表" message="展示名单主要信息等">
    <!-- 搜索表单 -->
    <div>
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="用户ID">
          <el-input
            v-model.number="searchForm.userId"
            placeholder="请输入用户ID"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input
            v-model.number="searchForm.userName"
            placeholder="请输入用户名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="SKU ID">
          <el-input
            v-model.number="searchForm.skuId"
            placeholder="请输入SKU ID"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="属性值">
          <el-input
            v-model="searchForm.pvValue"
            placeholder="请输入属性值"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.orderStatus"
            placeholder="请选择订单状态"
            style="width: 200px"
            clearable
          >
            <el-option v-for="(v, k) in orderStatusMap" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="gotoPlaceOrder" style="text-align: right">
            创建订单
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <el-table :data="orderList" style="width: 100%" v-loading="loading" border>
      <el-table-column prop="orderId" label="订单ID" />
      <el-table-column prop="orderNo" label="订单号" />
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          {{ scope.row.orderStatus }}
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="payAmount" label="支付金额">
        <template #default="scope"> ¥{{ scope.row.payAmount }}</template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="createdAt" label="创建时间">
        <template #default="scope">
          {{ scope.row.createdAt }}
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间">
        <template #default="scope">
          {{ scope.row.updatedAt }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <div class="button-container">
            <el-button size="small" type="info" @click="jumpDetailPage(scope.row)">查看</el-button>
            <el-button size="small" type="danger" @click="deleteOrder(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />
  </ContentWrap>
</template>

<style scoped>
.button-container {
  display: flex;
  flex-direction: column; /* 垂直排列，实现换行效果 */
  align-items: center; /* 右对齐 */
  gap: 8px; /* 按钮间距 */
}
.button-container :deep(.el-button) {
  margin: 0; /* 重置按钮默认外边距 */
}
</style>
